package secondBrush.doubles;


import java.util.Currency;

public class E08Leetcode19 {
    public  E07Leetcode24.ListNode removeNthFromEnd(E07Leetcode24.ListNode head, int n) {
        //找到正数 n 个节点
        int pre = size(head) - n;
        E07Leetcode24.ListNode dummy = new E07Leetcode24.ListNode(-1);
        dummy.next = head;
        E07Leetcode24.ListNode cur = dummy;
        for (int i = 0; i < pre; i++) {
            cur = cur.next;
        }
        cur.next = cur.next.next;
        return dummy.next;
    }



    private int size(E07Leetcode24.ListNode head) {
        E07Leetcode24.ListNode cur = head;
        int size = 0;
        while (cur != null) {
            size++;
            cur = cur.next;

        }
        return size;
    }

    public   ListNode removeNthFromEnd2(ListNode head, int n) {

        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode fast = dummy;
        ListNode slow = dummy;
        for (int i = 0; i <= n ; i++) {
            fast = fast.next;
        }
        while (fast != null) {
            slow = slow.next;
            fast = fast.next;
        }

        if (slow.next != null) {

            slow.next = slow.next.next;
        }
        return dummy.next;


    }

    public static class ListNode {
        int val;
       ListNode next;
        ListNode() {}
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }







    public static void main(String[] args) {
        E07Leetcode24.ListNode head = new E07Leetcode24.ListNode(1, new E07Leetcode24.ListNode(2, new E07Leetcode24.ListNode(3, new E07Leetcode24.ListNode(4, new E07Leetcode24.ListNode(5, null)))));
        E08Leetcode19 e08Leetcode19 = new E08Leetcode19();
        e08Leetcode19.removeNthFromEnd(head, 2);

    }
}
